﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Windows;
using System.IO;

namespace AJWPFAdmin.Core.Utils
{
    public static class BitmapSourceConvert
    {
        /// <summary>
        /// Delete a GDI object
        /// </summary>
        /// <param name="o">The poniter to the GDI object to be deleted</param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);

        /// <summary>
        /// Convert an IImage to a WPF BitmapSource. The result can be used in the Set Property of Image.Source
        /// </summary>
        /// <param name="image">The Emgu CV Image</param>
        /// <returns>The equivalent BitmapSource</returns>
        public static BitmapSource ToBitmapSource(System.Drawing.Bitmap image)
        {
            //using (image)
            //{
            //    IntPtr ptr = image.GetHbitmap(); //obtain the Hbitmap

            //    BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
            //        ptr,
            //        IntPtr.Zero,
            //        Int32Rect.Empty,
            //        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

            //    if (!DeleteObject(ptr))
            //    {
            //        throw new System.ComponentModel.Win32Exception();
            //    }
            //    return bs;
            //}

            BitmapImage bs = null;
            try
            {
                var ms = new MemoryStream();

                image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                bs = new BitmapImage();
                bs.BeginInit();
                ms.Seek(0, SeekOrigin.Begin);
                bs.StreamSource = ms;
                bs.EndInit();

            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine($"ToBitmapSource Exception:{e.Message}");
            }

            return bs;
        }
    }
}
